package com.changlie.generator.test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.changlie.generator.dao.CommonDao;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

public class JsEngineDemo {

	public static void main(String[] args) throws Exception {
		Invocable invoker = getSecriptInvoker("/script/formula.js");
		CommonDao dao = new CommonDao();
		invoker.invokeFunction("initDao", dao);
		invoker.invokeFunction("testDao");
	}
	
	

	static void test1() throws Exception {
		
		String filepath  = "/script/salary.js";
		Invocable invoker = getSecriptInvoker(filepath);
		System.out.println(invoker.invokeFunction("getSalary", "lining"));
		System.out.println(invoker.invokeFunction("getSalary", "waiter"));
		
		Jdbc jdbc = new Jdbc();
		invoker.invokeFunction("initDao", jdbc);
		invoker.invokeFunction("useDao");
		
		List<String> list = new ArrayList<String>();
		list.add("tome");
		list.add("joy");
		list.add("zoe");
		invoker.invokeFunction("testList", list);
		
		ScriptObjectMirror ret = (ScriptObjectMirror) invoker.invokeFunction("getJSONObj");
		System.out.println(ret.getClass().getTypeName());
		System.out.println(ret);
		for (String key : ret.keySet()) {
			System.out.println(key+" => "+ret.get(key));
		}
		
		System.out.println(invoker.invokeFunction("getCode"));
		
		ScriptEngine engine = getScriptEngine();
		System.out.println(engine.eval("10.0 /3").getClass().getTypeName()+", "+engine.eval("10.0 /3"));
		engine.eval("i = 22.1"); 
		engine.put("j", 15); 
		engine.eval("z = i + j"); 
		System.out.println(engine.get("z").getClass()+", "+engine.get("z"));
	}



	private static ScriptEngine getScriptEngine() {
		return new ScriptEngineManager().getEngineByName("nashorn");
	}

	private static Invocable getSecriptInvoker(String filepath) throws FileNotFoundException, ScriptException {
		URL url = JsEngineDemo.class.getClassLoader().getResource("");
		System.out.println("=> "+url);
		ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
		engine.eval(new FileReader(url.getFile()+filepath));
		Invocable invocable = (Invocable) engine;
		return invocable;
	}
}
